﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;


namespace WHLRDF.Web
{
    /// <summary>
    /// 应用程序启动类
    /// </summary>
    public class ApplicationManagerService: IApplicationManagerService
    {
        private readonly static object _thisLock = new object();
        private static ApplicationManagerService _ApplicationInstance;
        public static ApplicationManagerService Instance
        {
            get
            {
                if (_ApplicationInstance == null)
                {
                    lock (_thisLock)
                    {
                        if (_ApplicationInstance == null)
                        {
                            _ApplicationInstance = new ApplicationManagerService();
                        }
                    }
                }
                return _ApplicationInstance;
            }
        }
      
        private IHostBuilder _web;
        private CancellationTokenSource _tokenSource;
        private bool _running;
        private bool _restart;

        public bool Restarting => _restart;

        public ApplicationManagerService()
        {
            _running = false;
            _restart = false;

        }

        public void Start()
        {
            if (_running)
                return;
            if (_tokenSource != null && _tokenSource.IsCancellationRequested)
                return;

            _tokenSource = new CancellationTokenSource();
            _tokenSource.Token.ThrowIfCancellationRequested();
            _running = true;

            _web = new HostBuilder()
              .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.ConfigureKestrel(serverOptions =>
                    {
                        // Set properties and call methods on options
                    })
                    .ConfigureLogging(logging => {
                      
                        logging.AddConsole();
                    })
                    .UseContentRoot(Directory.GetCurrentDirectory())
               .UseStartup<Startup>();

                });


            _web.Build().RunAsync(_tokenSource.Token).GetAwaiter().GetResult();
        }

        public void Stop()
        {
            if (!_running)
                return;

            _tokenSource.Cancel();
            _running = false;
        }

        public void Restart()
        {
            Stop();

            _restart = true;
            _tokenSource = null;
        }
    }
}
